package com.moneyhelper.upms.interceptor;

import cn.hutool.core.util.StrUtil;
import com.moneyhelper.upms.constant.RedisKey;
import com.moneyhelper.upms.handler.ContextHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author： ygl
 * @date： 2019/07/07
 * @Description：
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String authorization = request.getHeader("Authorization");
        if (!StrUtil.isEmpty(authorization)) {
            String userId = stringRedisTemplate.opsForValue().get(RedisKey.userToken + authorization);
            if (!StrUtil.isEmpty(userId)) {
                ContextHandler.setUserId(userId);
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().write("登录信息已失效");
        return false;

    }
}
